package com.lindroy.androidplayer.base

import androidx.databinding.ViewDataBinding
import com.elvishew.xlog.XLog

/**
 * @author Lin
 * @date 2022/1/10
 * @function Fragment 懒加载
 */
abstract class BaseLazyFragment<VB : ViewDataBinding> : BaseFragment<VB>() {


    /**
     * 是否已经执行过懒加载
     */
    private var isLoaded = false

    /**
     * 当前Fragment是否对用户可见，对外只读
     */
    var isVisibleToUser = false
        private set

    /**
     * onResume方法是否执行
     */
    private var isResume = false

    /**
     * 是否调用了setUserVisibleHint方法。处理show+add+hide模式下，默认可见 Fragment 不调用
     * onHiddenChanged 方法，进而不执行懒加载方法的问题。
     */
    private var isCallUserVisibleHint = false

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        isVisibleToUser = hidden.not()
        judgeLazyLoad()
    }

    private fun judgeLazyLoad() {
        if (isLoaded.not() && isVisibleToUser && isResume) {
            lazyLoad()
            isLoaded = true
        }
    }

    override fun onResume() {
        super.onResume()
        isResume = true
        //如果onHiddenChanged方法没有调用的话，isVisibleToUser的值是不会改变的，这里需要赋值
        if (isCallUserVisibleHint.not()) {
            isVisibleToUser = isHidden.not()
        }
        judgeLazyLoad()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isLoaded = false
        isResume = false
        isCallUserVisibleHint = false
        isVisibleToUser = false
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleToUser = isVisibleToUser
        judgeLazyLoad()
    }

    override fun initData() {}

    abstract fun lazyLoad()
}